<template>
  <div class="main">
    <div class="filter">
      <el-input placeholder="请输入客户名" type="small" v-model="form.khname" clearable></el-input>
      <el-row>
        <el-col :span="16">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 95%;"
            placeholder="开始时间"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" class="el-icon-search" @click="getThatDayData" style="width: 100%;">当天所有</el-button>
        </el-col>
        <el-col :span="16">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 95%;"
            placeholder="结束时间"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" class="el-icon-search" @click="searchBill" style="width: 100%;">查 询</el-button>
        </el-col>
        <el-col :span="24" style="margin:10px">
          <span style="font-size: 0.9rem;font-family: 'PingFang SC';">排序：</span>
          <el-radio v-model="radio" label="dh">单号</el-radio>
          <el-radio v-model="radio" label="rq">时间</el-radio>
          <el-radio v-model="radio" label="je">金额</el-radio>
          <el-radio v-model="radio" label="ml">毛利</el-radio>
        </el-col>
        <el-col :span="24">
          <el-button size="mini" style="width: 100%;" @click="getQuest">有问题单</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="sum">共{{result.length}}张单，总金额￥{{totalJe}}<br/>总欠款￥{{totalQk}}，毛利￥{{totalMl}}</div>
    <div class="result-dj">
      <div class="box"
           :class="{active: activeIndex === item.dh}"
           :id="'list'+ item.dh"
           v-for="(item,index) in result"
           @click="clickItem(item.dh)"
      >
        <div class="custName">
          {{ item.khname }}
          <div class="title-count">
            <span class="ml" :class="item.ml > 0? 'yl' : 'kq'">￥{{item.ml}}</span>
            <span class="ml-icon" :class="item.ml > 0? 'yl' : 'kq'">{{ item.ml > 0? '盈' : '亏' }}</span>
            <span class="je" :class="{qk: item.fkfs === '欠款', jj: item.fkfs === '即结'}">￥{{ item.je }}</span>
            <span class="je-icon" :class="{qk: item.fkfs === '欠款', jj: item.fkfs === '即结'}">{{ item.fkfs }}</span>
          </div>
        </div>
        <div class="hide-content">
          <div class="content-item">单号：{{ item.dh }}</div>
          <div class="content-item">日期：{{ item.rq }}</div>
          <div class="content-item">毛利：￥{{ item.ml }}</div>
        </div>
      </div>
      <div class="no-more">没有更多数据啦</div>
    </div>
    <div class="dj-detail" ref="djDetail" :class="collapse ? 'collapse' : ''">
      <div class="dj-title">
        <template v-if="curCust">
          <div>{{ curCust.khname }}</div>
          <div class="total-flex">
            <div class="ml" :class="curCust.ml > 0 ? 'yl' : 'kq'">￥{{ curCust.ml }}</div>
            <div class="total" :class="{qk: curCust.fkfs === '欠款', jj: curCust.fkfs === '即结'}">￥{{ curCust.je }}</div>
            <i class="el-icon-arrow-down" @click="collapse = !collapse"></i>
          </div>
        </template>
      </div>
      <div class="dj-list">
        <div class="dj-list-item" v-for="item in result_detail[activeIndex]">
          <div class="spname" @click="checkKc(item.spbh)">{{ item.spname }}</div>
          <div class="sl" v-if="item.prnjs.indexOf('0.00') === 0">{{ item.prnxs }}</div>
          <div class="sl" v-else>{{ item.prnjs }}</div>
          <div class="xj">小计: ￥{{ (item.sl * item.jg).toFixed(2) }}</div>
          <div class="dj">单价: ￥{{ item.jg.toFixed(2) }}</div>
          <div class="jj">进价: ￥{{ item.jj.toFixed(2) }}</div>
          <div class="ml">毛利: <span :style="{color: item.jg > item.jj ? '#67c23a' : '#dd6161'}"
          >￥{{ ((item.jg - item.jj) * item.sl).toFixed(2) }}</span>
          </div>
          <div class="kc-change">{{ item.line }}</div>
        </div>
      </div>
      <el-dialog :visible="goodStorageDialog" title="库存信息" :before-close="handleClose" width="80%" append-to-body>
        <div v-if="kcInf">
          <h2>{{kcInf.spname}}库存信息</h2>
          <div class="view-line">
            <div class="title">门市库存</div>
            <div class="value">{{ kcInf.mskc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">门市可用</div>
            <div class="value">{{ kcInf.msky + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">仓库库存</div>
            <div class="value">{{ kcInf.ckkc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">仓库可用</div>
            <div class="value">{{ kcInf.ckky + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">大昌库存</div>
            <div class="value">{{ kcInf.dckc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">远洋库存</div>
            <div class="value">{{ kcInf.yykc + kcInf.dw2 }}</div>
          </div>
        </div>
      </el-dialog>
    </div>

    <div class="mask" v-if="result_loading" v-loading="result_loading" element-loading-text="正在拼命加载中"></div>
  </div>
</template>

<script>
import {
  queryZD,
  getRecentZD,
  getZDdetail,
  getThatDayZD,
  hasReadZd,
  hasQuestZd,
  getQuestZD,
  queryGoods
} from '@/api/goods'
import ListContent from '@/components/ListContent'
import { compare } from '@/utils/common'

export default {
  components: {
    ListContent
  },
  name: 'ZDQuery',
  watch: {
    /* 监听排序方式 */
    radio(newValue) {
      // 收起折叠框
      this.collapse = true
      this.result = this.result.sort(compare(newValue))
    },
    activeIndex() {
      this.collapse = true
      setTimeout(() => {
        this.collapse = false
      }, 500)
    },
    result() {
      this.calcTotal()
    }
  },
  computed: {
    curCust() {
      return this.result.filter((x) => x.dh === this.activeIndex)[0]
    }
  },
  data() {
    return {
      form: {
        khname: '',
        startTime: '',
        endTime: ''
      },
      result: [],
      result_detail: [],
      result_loading: false,
      activeIndex: 0,
      collapse: false,
      intervalId: null,
      goodStorageDialog: false,
      kcInf: null,
      radio: 'dh',
      totalJe: 0,
      totalMl: 0,
      totalQk: 0
    }
  },
  methods: {
    /* 计算总值 */
    calcTotal() {
      let totalJe = 0, totalMl = 0, totalQk = 0
      this.result.forEach((each) => {
        totalJe += each.je
        totalMl += each.ml
        totalQk += each.qk
      })
      this.totalJe = totalJe.toFixed(2)
      this.totalMl = totalMl.toFixed(2)
      this.totalQk = totalQk.toFixed(2)
    },
    /* 搜索账单 */
    searchBill() {
      if (this.form.khname !== '') {
        this.result_loading = true
        queryZD(this.form).then(res => {
          if (res.code === 200) {
            this.result = res.data.zd
            this.result_detail = res.data.zd_detail
            if (res.data.zd.length) {
              let totalJe = 0, totalMl = 0
              res.data.zd.forEach((each) => {
                each.collapse = false
                totalJe += each.je
                totalMl += each.qk
              })
              this.totalJe = totalJe.toFixed(2)
              this.totalMl = totalMl.toFixed(2)
            } else {
              this.$message.warning('无数据')
            }
          }
        }).finally(() => {
          this.result_loading = false
          this.currentIndex = null
        })

        this.$buryingPoint('查询出货账单', JSON.stringify(this.form))
      } else {
        // 为空时获取最近的账单
        getRecentZD().then((res) => {
          this.result = res.data.zd
          this.result.forEach((each) => {
            each.collapse = false
          })
          this.result_detail = res.data.zd_detail
          this.currentIndex = null
        })

        this.$buryingPoint('查询出货账单-最近', null)
      }
    },
    async clickItem(dh) {
      this.activeIndex = dh
      this.collapse = false
      await this.$nextTick()
      let offsetTop = document.getElementById(`list${dh}`).offsetTop
      console.log(offsetTop)
      window.scrollTo({ left: 0, top: offsetTop + 40, behavior: 'smooth' })
    },
    async checkKc(spbh) {
      let result = await queryGoods(spbh)
      console.log(result)
      this.kcInf = result.data[0]
      this.goodStorageDialog = true
    },
    handleChange(val) {
      if (val !== '') {

        this.currentIndex = val

        window.setTimeout(() => {
          this.jumpToCurrent()
        }, 500)

        this.detail_data = this.result_detail[this.result[val].dh]
        this.detail_collaspe = true

      }
    },
    handleClose() {
      this.goodStorageDialog = false
    },
    getThatDayData() {
      let startTime = this.form.startTime
      let data = {
        thatDay: startTime
      }
      this.result_loading = true
      getThatDayZD(data).then((res) => {
        this.result = res.data.zd.sort(compare(this.radio))
        this.result_detail = res.data.zd_detail
      }).finally(() => {
        this.result_loading = false
        this.currentIndex = null
        this.detail_collaspe = false
      })

      this.$buryingPoint('查询出货账单-当天', JSON.stringify(this.form))
    }
    ,
    /* 执行跳转滑动动作 */
    jumpToCurrent() {
      let target = document.getElementById(this.currentIndex)
      this.$nextTick(() => {
        window.scrollTo(0, target.offsetTop + 50)
      })

      // let currentRoute = this.$route.path
      // let a = document.createElement('a')
      // a.href = '#' + this.currentIndex
      // let body = document.querySelector('body')
      // body.appendChild(a)
      // a.click()
      // body.removeChild(a)
      // this.$router.push(currentRoute)
    }
    ,
    hasRead() {
      let dh = this.result[this.currentIndex].dh
      this.result[this.currentIndex].isRead = '1'
      hasReadZd(dh, 1).then(res => {
        console.log(res.msg)
      })

      if (this.currentIndex !== this.result.length - 1) {
        let num = this.currentIndex + 1
        this.$refs.collapse.setActiveNames(num)
        setTimeout(() => {
          this.jumpToCurrent()
        }, 1500)
      }
    }
    ,
    hasQuest() {
      let dh = this.result[this.currentIndex].dh
      this.result[this.currentIndex].isRead = '2'
      hasQuestZd(dh, 1).then(res => {
        console.log(res.msg)
      })

      if (this.currentIndex !== this.result.length - 1) {
        let num = this.currentIndex + 1
        this.$refs.collapse.setActiveNames(num)
        setTimeout(() => {
          this.jumpToCurrent()
        }, 1500)
      }
    }
    ,
    getQuest() {
      this.result_loading = true
      getQuestZD(1).then(res => {
        this.currentIndex = null
        this.detail_collaspe = false
        this.result = res.data.zd
        this.result_detail = res.data.zd_detail
        // this.calcTotal()
      }).finally(() => {
        this.result_loading = false
      })
    }
  },
  created() {
    // 初始化选择时间
    const date = new Date()
    const date2 = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
    this.form.startTime = date.toLocaleDateString().replace(/\//g, '-')
    this.form.endTime = date2.toLocaleDateString().replace(/\//g, '-')

  },
  mounted() {
    this.result_loading = true
    getRecentZD().then((res) => {
      this.result = res.data.zd.sort(compare(this.radio))
      this.result.forEach((each) => {
        each.collapse = false
      })
      this.result_detail = res.data.zd_detail
    }).finally(() => {
      if(this.result.length !== 0) {
        this.activeIndex = this.result[0].dh
      }
      this.result_loading = false
    })

    this.$buryingPoint('查询出货账单-最近', null)
  }
}
</script>

<style lang="scss" scoped>
.main {
  max-width: 600px;
  padding: 10px;

  .filter {
    .el-input {
      margin-bottom: 5px;
    }

    .el-date-editor {
      margin-right: 10px;
    }
  }

  .sum {
    font-size: 10px;
    color: #999999;
    text-align: center;
    margin-top: 10px;
  }
  .result-dj {
    margin-top: 10px;
    padding-bottom: 70vh;

    .no-more {
      font-size: 8px;
      color: #999999;
      width: 100%;
      text-align: center;
      margin-top: 20px;
    }

    .box {
      width: 100%;
      border: 1px solid #DCDFE6;
      border-radius: 8px;
      margin-bottom: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 10px;
      transition: height 0.5s ease;

      &.active {
        border: 2px solid #4271ff;
      }

      .custName {
        width: 100%;
        font-size: 12px;
        display: inline-flex;
        justify-content: space-between;
        color: #666666;

        .title-count {
          display: inline-flex;
          align-items: center;
        }

        .ml {
          font-weight: bold;
          font-size: 10px;
          margin-right: 10px;
          &.yl {
            color: #67c23a;
          }

          &.kq {
            color: #dd6161;
          }
        }

        .ml-icon {
          display: inline-flex;
          align-items: center;
          margin-right: 8px;
          color: #fff;
          background-color: #dd6161;
          padding: 3px;
          font-weight: bold;
          border-radius: 4px;
          font-size: 8px;
          &.yl {
            background-color: #67c23a;
          }
        }

        .je {
          font-weight: bold;
          font-size: 14px;

          &.qk {
            color: #dd6161;
          }

          &.jj {
            color: #67c23a;
          }
        }
        .je-icon {
          display: inline-flex;
          align-items: center;
          margin-left: 8px;
          color: #fff;
          background-color: #dd6161;
          font-size: 8px;
          padding: 3px;
          border-radius: 4px;
          font-weight: bold;
          &.jj {
            background-color: #67c23a;
          }
        }
      }

      .hide-content {
        margin-top: 10px;
        padding: 5px 0 0 0;
        border-top: 1px solid #DCDFE6;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .content-item {
          width: 50%;
          font-size: 12px;
          line-height: 18px;
          color: #666666;
        }
      }
    }
  }

  .dj-detail {
    position: fixed;
    max-width: 600px;
    width: 100vw;
    bottom: 0;
    left: 0;
    border-radius: 8px 8px 0 0;
    transition: all 0.5s ease;
    &.collapse {
      bottom: -50vh;
    }

    .dj-title {
      width: 100%;
      height: 30px;
      background-color: #e1dfdf;
      display: inline-flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      border-top: 1px solid #DCDFE6;
      border-bottom: 1px solid #DCDFE6;
      font-size: 12px;
      color: #666666;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 8px 8px 0 0;

      .total-flex {
        display: inline-flex;
        align-items: center;
      }

      .ml {
        font-weight: bold;
        font-size: 10px;
        margin-right: 10px;
        &.yl {
          color: #67c23a;
        }

        &.kq {
          color: #dd6161;
        }
      }

      .total {
        font-weight: bold;
        margin-right: 10px;

        &.qk {
          color: #dd6161;
        }

        &.jj {
          color: #67c23a;
        }
      }
    }

    .dj-list {
      background-color: #f1f1f1;
      font-size: 12px;
      color: #666666;
      padding-bottom: 40px;
      max-height: 45vh;
      min-height: 25vh;
      overflow: scroll;
      overscroll-behavior: none;

      .dj-list-item {
        padding: 0 10px;
        width: 100%;
        line-height: 18px;
        border-bottom: 1px solid #DCDFE6;
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .spname {
          width: 45%;
          font-weight: bold;
        }

        .dj {
          width: 45%;
        }

        .sl, .jj {
          width: 30%;
        }

        .xj, .ml {
          width: 25%;
          text-align: right;
        }

        .dj, .jj, .ml {
          background-color: #f1f1f1;
        }

        & > div {
          line-height: 25px;
          height: 25px;
          border-bottom: 1px solid #DCDFE6;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.view-line {
  display: inline-flex;
  justify-content: space-between;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  width: 100%;
}

html {
  scroll-behavior: smooth;
}

.mask {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
}
</style>
